<template>
  <div class="performance-statistics-page">
    <div class="header">
      <h2>客服绩效统计</h2>
    </div>
    <el-card class="filter-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="统计时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="客服">
          <el-select v-model="searchForm.staffId" placeholder="全部客服" clearable style="width: 180px;">
            <el-option v-for="staff in staffList" :key="staff.id" :label="staff.name" :value="staff.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="exportData">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="charts-container">
      <el-card class="chart-card-large">
        <v-chart class="chart" :option="trendChartOption" autoresize />
      </el-card>
      <el-card class="chart-card-small">
        <v-chart class="chart" :option="rankingChartOption" autoresize />
      </el-card>
    </div>

    <div class="overview-cards">
      <el-card class="overview-card">
        <div class="overview-title">总会话数</div>
        <div class="overview-value">{{ summary.totalSessions }}</div>
      </el-card>
      <el-card class="overview-card">
        <div class="overview-title">平均响应时长</div>
        <div class="overview-value">{{ summary.avgResponseTime }} 秒</div>
      </el-card>
      <el-card class="overview-card">
        <div class="overview-title">平均会话时长</div>
        <div class="overview-value">{{ summary.avgSessionTime }} 分钟</div>
      </el-card>
      <el-card class="overview-card">
        <div class="overview-title">满意度</div>
        <div class="overview-value">{{ summary.satisfaction }} 分</div>
      </el-card>
    </div>
    <el-card class="table-card">
      <el-table :data="pagedData" border stripe style="width: 100%;">
        <el-table-column prop="name" label="客服姓名" width="120">
          <template #default="{ row }">
            <el-link type="primary" @click="showStaffDetail(row)">{{ row.name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="totalSessions" label="会话数" sortable width="100" />
        <el-table-column prop="activeSessions" label="进行中" sortable width="100" />
        <el-table-column prop="closedSessions" label="已结束" sortable width="100" />
        <el-table-column prop="firstResponseTime" label="首次响应(秒)" sortable width="140" />
        <el-table-column prop="avgResponseTime" label="平均响应(秒)" sortable width="140" />
        <el-table-column prop="avgSessionTime" label="平均会话(分钟)" sortable width="160" />
        <el-table-column prop="satisfaction" label="满意度" sortable width="100" />
        <el-table-column prop="fcr" label="首次解决率" sortable width="130">
          <template #default="{ row }">
            {{ (row.fcr * 100).toFixed(0) }}%
          </template>
        </el-table-column>
        <el-table-column prop="evaluationRate" label="参评率" sortable width="100">
          <template #default="{ row }">
            {{ (row.evaluationRate * 100).toFixed(0) }}%
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 18px; justify-content: flex-end;"
      />
    </el-card>

    <el-dialog v-model="staffDetailDialog.visible" :title="`${staffDetailDialog.staff?.name} - 个人绩效详情`" width="800px">
      <div v-if="staffDetailDialog.staff">
        <v-chart class="chart" :option="staffDetailChartOption" autoresize />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
]);


const staffList = ref([
  { id: 'A', name: '客服A' },
  { id: 'B', name: '客服B' },
  { id: 'C', name: '客服C' },
  { id: 'D', name: '客服D' },
]);

const allData = ref([
  { id: 'A', name: '客服A', totalSessions: 32, activeSessions: 3, closedSessions: 29, avgResponseTime: 18, firstResponseTime: 12, avgSessionTime: 12, satisfaction: 4.8, fcr: 0.85, evaluationRate: 0.6 },
  { id: 'B', name: '客服B', totalSessions: 27, activeSessions: 2, closedSessions: 25, avgResponseTime: 22, firstResponseTime: 15, avgSessionTime: 15, satisfaction: 4.6, fcr: 0.80, evaluationRate: 0.55 },
  { id: 'C', name: '客服C', totalSessions: 19, activeSessions: 1, closedSessions: 18, avgResponseTime: 15, firstResponseTime: 10, avgSessionTime: 10, satisfaction: 4.9, fcr: 0.92, evaluationRate: 0.7 },
  { id: 'D', name: '客服D', totalSessions: 15, activeSessions: 0, closedSessions: 15, avgResponseTime: 20, firstResponseTime: 18, avgSessionTime: 13, satisfaction: 4.7, fcr: 0.88, evaluationRate: 0.65 },
]);

const dailyTrendData = ref([
  { date: '2024-06-01', totalSessions: 15, avgResponseTime: 20 },
  { date: '2024-06-02', totalSessions: 18, avgResponseTime: 18 },
  { date: '2024-06-03', totalSessions: 22, avgResponseTime: 16 },
  { date: '2024-06-04', totalSessions: 19, avgResponseTime: 19 },
  { date: '2024-06-05', totalSessions: 25, avgResponseTime: 15 },
  { date: '2024-06-06', totalSessions: 28, avgResponseTime: 14 },
  { date: '2024-06-07', totalSessions: 26, avgResponseTime: 17 },
]);

const searchForm = ref({
  dateRange: [],
  staffId: '',
});

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
});

const filteredData = computed(() => {
  let list = allData.value;
  if (searchForm.value.staffId) {
    list = list.filter(item => item.id === searchForm.value.staffId);
  }
  // 时间筛选可根据实际数据结构补充
  return list;
});

const pagedData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return filteredData.value.slice(start, end);
});

const trendChartOption = computed(() => {
  // 模拟基于时间的数据
  const dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const sessionsData = [120, 132, 101, 134, 90, 230, 210];
  const responseTimeData = [22, 18, 19, 23, 29, 33, 31];

  return {
    title: {
      text: '绩效趋势分析'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总会话数', '平均响应时长']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '会话数',
        position: 'left',
      },
      {
        type: 'value',
        name: '响应时长(秒)',
        position: 'right',
        inverse: true
      }
    ],
    series: [
      {
        name: '总会话数',
        type: 'line',
        stack: 'Total',
        data: sessionsData,
        yAxisIndex: 0
      },
      {
        name: '平均响应时长',
        type: 'line',
        stack: 'Time',
        data: responseTimeData,
        yAxisIndex: 1
      }
    ]
  };
});

const rankingChartOption = computed(() => {
  const data = allData.value
    .slice() // 创建副本以避免修改原始数据
    .sort((a, b) => a.totalSessions - b.totalSessions);

  return {
    title: {
      text: '客服会话量排行',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '会话数',
        type: 'bar',
        data: data.map(item => item.totalSessions)
      }
    ]
  };
});


const summary = computed(() => {
  const list = filteredData.value;
  if (!list.length) return { totalSessions: 0, avgResponseTime: 0, avgSessionTime: 0, satisfaction: 0 };
  const totalSessions = list.reduce((sum, item) => sum + item.totalSessions, 0);
  const avgResponseTime = Math.round(list.reduce((sum, item) => sum + item.avgResponseTime, 0) / list.length);
  const avgSessionTime = Math.round(list.reduce((sum, item) => sum + item.avgSessionTime, 0) / list.length);
  const satisfaction = (list.reduce((sum, item) => sum + item.satisfaction, 0) / list.length).toFixed(2);
  return { totalSessions, avgResponseTime, avgSessionTime, satisfaction };
});

const staffDetailDialog = ref({
  visible: false,
  staff: null as any,
});

const staffDetailChartOption = computed(() => {
  if (!staffDetailDialog.value.staff) return {};
  const staff = staffDetailDialog.value.staff;
  const dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  // 模拟个人数据
  const sessionsData = dates.map(() => Math.round(staff.totalSessions / 7 + (Math.random() - 0.5) * 5));
  const responseTimeData = dates.map(() => Math.round(staff.avgResponseTime + (Math.random() - 0.5) * 5));

  return {
    title: { text: '个人绩效趋势' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['会话数', '平均响应时长'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: dates },
    yAxis: [
      { type: 'value', name: '会话数', position: 'left' },
      { type: 'value', name: '响应时长(秒)', position: 'right', inverse: true }
    ],
    series: [
      { name: '会话数', type: 'line', data: sessionsData, yAxisIndex: 0 },
      { name: '平均响应时长', type: 'line', data: responseTimeData, yAxisIndex: 1 }
    ]
  };
});


function handleSearch() {
  pagination.value.currentPage = 1;
}
function resetSearch() {
  searchForm.value.dateRange = [];
  searchForm.value.staffId = '';
  pagination.value.currentPage = 1;
}
function handleSizeChange(val: number) {
  pagination.value.pageSize = val;
}
function handleCurrentChange(val: number) {
  pagination.value.currentPage = val;
}
function exportData() {
  // 简单导出为 CSV
  const header = '客服姓名,会话数,进行中,已结束,首次响应(秒),平均响应时长(秒),平均会话时长(分钟),满意度,首次解决率,参评率';
  const rows = filteredData.value.map(item => [item.name, item.totalSessions, item.activeSessions, item.closedSessions, item.firstResponseTime, item.avgResponseTime, item.avgSessionTime, item.satisfaction, item.fcr, item.evaluationRate].join(','));
  const csv = [header, ...rows].join('\n');
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = '客服绩效统计.csv';
  a.click();
  URL.revokeObjectURL(url);
  ElMessage.success('导出成功');
}

function showStaffDetail(staff: any) {
  staffDetailDialog.value.staff = staff;
  staffDetailDialog.value.visible = true;
}
</script>

<style scoped>
.performance-statistics-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.header h2 {
  margin: 0;
  color: #333;
}
.filter-bar {
  margin-bottom: 18px;
}
.overview-cards {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
}
.overview-card {
  flex: 1;
  text-align: center;
  padding: 18px 0;
}
.overview-title {
  color: #888;
  font-size: 15px;
  margin-bottom: 8px;
}
.overview-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}
.table-card {
  margin-top: 12px;
}
.charts-container {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
}
.chart-card-large {
  flex: 2;
}
.chart-card-small {
  flex: 1;
}
.chart {
  height: 400px;
}
</style> 